package com.happyma.bbn.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.happyma.bbn.R;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class AsyncJSONURLsParser extends AsyncTask<String, String, String> implements CallbackReceiver{

    Activity activity;
    public ProgressDialog progressDialog;

    public AsyncJSONURLsParser(Activity paramActivity) {
        this.activity = paramActivity;
        String tip = ContextGeeter.getAppContext().getString(R.string.please_wait);
        progressDialog = new ProgressDialog(paramActivity);
        progressDialog.setMessage(tip);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(0);
        progressDialog.setCancelable(true);
    }

    @Override
    protected void onPreExecute() {
        String string = ContextGeeter.getAppContext().getString(R.string.please_wait);
        progressDialog = ProgressDialog.show(activity,"",string, false,false);
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        String urlStr = strings[0];
        String str = strings[1];
        if ((urlStr != null) && (str != null)){
            if (Common.isNetworkAvailable()){
                return startParsing(urlStr, str);
            }
            errorMessage(ContextGeeter.getAppContext().getString(R.string.error_json_1001));
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        if ((progressDialog != null) || (progressDialog.isShowing())){
            progressDialog.dismiss();
        }
        if (s != null) {
            receiveData(s);
        } else {
            errorMessage(ContextGeeter.getAppContext().getString(R.string.error_json_1001));
        }
    }

    private String startParsing(String urlStr, String str) {
        try {
            JSONObject jsonObject = new JSONObject(urlStr);
            urlStr = jsonObject.getJSONObject(str).getString(Common.getPreferredLanguageString());
            return urlStr;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


}
